//
//  ForgetViewController.m
//  SecondLoan
//
//  Created by 姚永波 on 2019/8/28.
//  Copyright © 2019 姚永波. All rights reserved.
//

#import "ForgetViewController.h"
#import "NSString+Tools.h"

@interface ForgetViewController ()<UITextFieldDelegate>

@property (nonatomic, assign) CGFloat lastSendcodeTime;
@property (strong, nonatomic) UITextField *txtPhone;
@property (strong, nonatomic) UITextField *txtCode;
@property (strong, nonatomic) UITextField *txtNewPwd;
@property (strong, nonatomic) UITextField *txtRepeatNewPwd;

@end

static CGFloat const lineSpace = 82.0f;

@implementation ForgetViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    [self setupViewForForgetPWD];
    self.txtNewPwd.secureTextEntry = YES;
    self.txtRepeatNewPwd.secureTextEntry = YES;
}
- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    [self.navigationController setNavigationBarHidden:YES animated:animated];
    self.navigationBarBgView.hidden = YES;
}

- (void)checkcodeDidClick:(UIButton *)sender {
    NSString * phone = [self.txtPhone text];
    if (phone.length != 11) return [self HUDshowErrorWithStatus:@"填写正确手机号"];
    NSString *urlStr = [NSString stringWithFormat:@"%@?phone=%@",HTTPAPIWITH(url_send_code),phone];
    [self HUDshowWithStatus:@""];
    sender.enabled = NO;
    [[PLRequestManage sharedInstance] httpRequestWithUrl:urlStr Type:RequestGet parameters:[NSMutableDictionary dictionary] completeHandle:^(id  _Nullable responseObject, NSError *error) {
        sender.enabled = YES;
        [self HUDdismiss];
        if (!error) {
            [self waitNextSend];
            [self HUDshowSuccessWithStatus:@"验证码已发送"];
        } else {
            [self HUDshowErrorWithStatus:error.localizedDescription];
        }
    }];
}

- (void)seePwdDidClick:(UIButton *)sender {
    sender.selected = !sender.selected;
    if (sender.selected) {
      [sender setImage: [UIImage imageNamed:@"seePWD.png"]forState:UIControlStateNormal];
      self.txtNewPwd.secureTextEntry = NO;
    }else{
      [sender setImage: [UIImage imageNamed:@"hidePWD.png"]forState:UIControlStateNormal];
      self.txtNewPwd.secureTextEntry = YES;
    }
}
- (void)seeRepeatPwdDidClick:(UIButton *)sender{
    sender.selected = !sender.selected;
    if (sender.selected) {
        [sender setImage: [UIImage imageNamed:@"seePWD.png"]forState:UIControlStateNormal];
        self.txtRepeatNewPwd.secureTextEntry = NO;
    }else{
        [sender setImage: [UIImage imageNamed:@"hidePWD.png"]forState:UIControlStateNormal];
        self.txtRepeatNewPwd.secureTextEntry = YES;
    }
}


- (void)submitClick:(UIButton *)sender{
    //调用接口 -- 如果修改成功直接调用登录接口进行登录 -- 登录成功后 回到我的首页
    NSString *phone = self.txtPhone.text;
    NSString *code = self.txtCode.text;
    if (isEmptyString(code)) {
        [self HUDshowErrorWithStatus:MsgHintVerifyCodeEmpty];
        return;
    }
    if (isEmptyString(self.txtCode.text)) {
        [self HUDshowErrorWithStatus:MsgHintVerifyCodeEmpty];
        return;
    }
    if (isEmptyString(self.txtNewPwd.text)) {
        [self HUDshowErrorWithStatus:MsgHintPasswordNeed];
        return;
    }
    if (isEmptyString(self.txtRepeatNewPwd.text)) {
        [self HUDshowErrorWithStatus:MsgHintNewPasswordSureNeed];
        return;
    }
    NSString *pwd = self.txtNewPwd.text;
    NSString *pwdRepeat = self.txtRepeatNewPwd.text;
    //检验密码是否符合规则
    if (self.txtNewPwd.text.length > 0) { //
        if(![self.txtNewPwd.text  judgePassWordLegal]) {
            [self HUDshowErrorWithStatus:MsgHintPasswordValid];
            return;
        }
        if (![pwd isEqualToString:pwdRepeat]) {
            [self HUDshowErrorWithStatus:@"两次新密码不相同"];
            return;
        }
    }
    NSMutableDictionary * param = [NSMutableDictionary dictionary];
    [param setObject:phone forKey:@"phone"];
    [param setObject:code forKey:@"messagecode"];
    [param setObject:pwd forKey:@"newpwd"];
    [self HUDshowWithStatus:@""];
    sender.enabled = NO;
    [[PLRequestManage sharedInstance] httpRequestWithUrl:HTTPAPIWITH(url_forgetPwd) Type:RequestPost parameters:param completeHandle:^(id  _Nullable responseObject, NSError *error) {
        [self HUDdismiss];
        sender.enabled = YES;
        if (!error) {
            [self HUDshowWithStatus:@"修改成功"];
            dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1.0 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                [self.navigationController popViewControllerAnimated: YES];
            });
        } else {
            [self HUDshowErrorWithStatus:error.localizedDescription];
        }
    }];
}

- (void)closeAction:(UIButton *)btn{
    [self.navigationController popViewControllerAnimated:YES];
}

- (void)setupViewForForgetPWD {
    self.view.fsBackGroundColor(0xffffff).develop(^(FFactory * factory){
        factory.imageView().fsImage(@"loginbg").fsImgContentMode(UIViewContentModeScaleAspectFill).fsFvid(@"bg_img");
        NSString *title = @"提交";        factory.imageView().fsImage(@"top_log").fsImgContentMode(UIViewContentModeScaleAspectFill).fsFvid(@"topLog");
        factory.label().fsFontSize(15.0).fsText(@"手机号").fsTextColor(0x23242A).fsFvid(@"phoneLabel");
        factory.textField().fsPlaceholder(@"请输入手机号").fsLimit(@"11").fsClearButtonMode(UITextFieldViewModeWhileEditing).fsFontSize(15.0).fsTextColor(0x23242A).fsKeyboard(UIKeyboardTypePhonePad).fsFvid(@"phoneField");
          factory.button().fsFontSize(15.0).fsText(@"获取验证码").fsAlign(NSTextAlignmentRight).fsTextColor(0xff4c2b).fsOnClick(checkcodeDidClick:).fsClip(YES).fsFvid(@"checkCodeBtn");
        factory.view().fsBackGroundColor(0xE5E5E5).fsFvid(@"seperLine1");
        //第二行
        factory.label().fsFontSize(15.0).fsText(@"短信验证码").fsTextColor(0x23242A).fsFvid(@"yzLabel");
        factory.textField().fsClearButtonMode(UITextFieldViewModeWhileEditing).fsPlaceholder(@"请输入短信验证码").fsLimit(@"11").fsFontSize(15.0).fsTextColor(0x23242A).fsKeyboard(UIKeyboardTypePhonePad).fsFvid(@"yzfield");
        factory.view().fsBackGroundColor(0xE5E5E5).fsFvid(@"seperLine2");
        
        
        factory.label().fsFontSize(15.0).fsText(@"新密码").fsTextColor(0x23242A).fsFvid(@"pwdLabel");
        factory.textField().fsClearButtonMode(UITextFieldViewModeWhileEditing).fsPlaceholder(@"8-16位数字字母组合密码").fsFontSize(15.0).fsTextColor(0x23242A).fsFvid(@"pwdfield");
        factory.button().fsImage(@"hidePWD").fsOnClick(seePwdDidClick:).fsClip(YES).fsFvid(@"seePwdCodeBtn");

        factory.view().fsBackGroundColor(0xE5E5E5).fsFvid(@"seperLine3");
        
        factory.label().fsFontSize(15.0).fsText(@"确认新密码").fsTextColor(0x23242A).fsFvid(@"pwdRepeatLabel");
        factory.textField().fsClearButtonMode(UITextFieldViewModeWhileEditing).fsPlaceholder(@"8-16位数字字母组合密码").fsFontSize(15.0).fsTextColor(0x23242A).fsFvid(@"pwdRepeatField");
        factory.button().fsImage(@"hidePWD").fsOnClick(seeRepeatPwdDidClick:).fsClip(YES).fsFvid(@"seeRepeatPwdCodeBtn");
        
        factory.view().fsBackGroundColor(0xE5E5E5).fsFvid(@"seperLine4");

        factory.button().fsFontSize(18.0).fsText(title).fsTextColor(0xffffff).fsOnClick(submitClick:).fsBackGroundImage(@"btn_bg").fsClip(YES).fsRadius(3.3).fsFvid(@"pushBtn");
        factory.button().fsOnClick(closeAction:).fsFontSize(15.0).fsImage(@"back-black").fsFvid(@"fClose");
        factory.button().fsOnClick(closeAction:).fsFontSize(15.0).fsFvid(@"fClose2");
    });
    // backgroundImg
    [fQuery(self.view, @"bg_img") mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(self.view.mas_left);
        make.centerX.equalTo(self.view.mas_centerX);
        make.centerY.equalTo(self.view.mas_centerY);
    }];
    // log
    [fQuery(self.view, @"topLog") mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(self.view.mas_top).with.offset(SCREEN_HEIGHT/6);
        make.left.equalTo(self.view).with.offset(92/750.0 * SCREEN_WIDTH);
        make.height.equalTo(@(80/750.0 * SCREEN_WIDTH));
    }];
    //第一行
    [fQuery(self.view, @"seperLine1") mas_makeConstraints:^(MASConstraintMaker *make) {
        make.bottom.equalTo(fQuery(self.view, @"topLog").mas_bottom).with.offset(235/750.0 * SCREEN_WIDTH);
        make.left.equalTo(self.view).with.offset(92/750.0 * SCREEN_WIDTH);
        make.right.equalTo(self.view).with.offset(-92/750.0 * SCREEN_WIDTH);
        make.height.equalTo(@1);
    }];
    [fQuery(self.view, @"checkCodeBtn") mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerY.equalTo(fQuery(self.view, @"phoneField"));
        make.right.equalTo(fQuery(self.view, @"seperLine1"));
        make.width.equalTo(@90);
        make.height.equalTo(@22);
    }];
    [fQuery(self.view, @"phoneField") mas_makeConstraints:^(MASConstraintMaker *make) {
        make.bottom.equalTo(fQuery(self.view, @"seperLine1").mas_top).with.offset(8);
        make.height.equalTo(@48);
        make.left.equalTo(fQuery(self.view, @"seperLine1"));
        make.right.equalTo(fQuery(self.view, @"checkCodeBtn")).with.offset(-85);
    }];

    [fQuery(self.view, @"phoneLabel") mas_makeConstraints:^(MASConstraintMaker *make) {
        make.bottom.equalTo(fQuery(self.view, @"phoneField").mas_top).with.offset(4);
        make.height.equalTo(@25);
        make.left.equalTo(fQuery(self.view, @"seperLine1"));
    }];
    //第二行
    [fQuery(self.view, @"seperLine2") mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(fQuery(self.view, @"seperLine1").mas_bottom).with.offset(lineSpace);
        make.left.equalTo(fQuery(self.view, @"seperLine1"));
        make.width.equalTo(fQuery(self.view, @"seperLine1"));
        make.height.equalTo(@1);
    }];
    [fQuery(self.view, @"yzfield") mas_makeConstraints:^(MASConstraintMaker *make) {
        make.bottom.equalTo(fQuery(self.view, @"seperLine2").mas_top).with.offset(8);
        make.height.equalTo(@48);
        make.left.equalTo(fQuery(self.view, @"seperLine2"));
        make.right.equalTo(fQuery(self.view, @"seperLine2"));
    }];
    [fQuery(self.view, @"yzLabel") mas_makeConstraints:^(MASConstraintMaker *make) {
        make.bottom.equalTo(fQuery(self.view, @"yzfield").mas_top).with.offset(4);
        make.height.equalTo(@25);
        make.left.equalTo(fQuery(self.view, @"seperLine2"));
    }];
    //第三行
    [fQuery(self.view, @"seperLine3") mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(fQuery(self.view, @"seperLine2").mas_bottom).with.offset(lineSpace);
        make.left.equalTo(fQuery(self.view, @"seperLine2"));
        make.width.equalTo(fQuery(self.view, @"seperLine2"));
        make.height.equalTo(@1);
    }];
    [fQuery(self.view, @"pwdfield") mas_makeConstraints:^(MASConstraintMaker *make) {
        make.bottom.equalTo(fQuery(self.view, @"seperLine3").mas_top).with.offset(8);
        make.height.equalTo(@48);
        make.left.equalTo(fQuery(self.view, @"seperLine3"));
        make.right.equalTo(fQuery(self.view, @"seperLine3")).with.offset(-30);;
    }];

    [fQuery(self.view, @"seePwdCodeBtn") mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerY.equalTo(fQuery(self.view, @"pwdfield"));
        make.right.equalTo(fQuery(self.view, @"pwdfield")).with.offset(30);
        make.width.equalTo(@44);
        make.height.equalTo(@44);
    }];
    [fQuery(self.view, @"pwdLabel") mas_makeConstraints:^(MASConstraintMaker *make) {
        make.bottom.equalTo(fQuery(self.view, @"pwdfield").mas_top).with.offset(4);
        make.height.equalTo(@25);
        make.left.equalTo(fQuery(self.view, @"seperLine3"));
    }];
    // 第四行
    [fQuery(self.view, @"seperLine4") mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(fQuery(self.view, @"seperLine3").mas_bottom).with.offset(lineSpace);
        make.left.equalTo(fQuery(self.view, @"seperLine3"));
        make.width.equalTo(fQuery(self.view, @"seperLine3"));
        make.height.equalTo(@1);
    }];
    [fQuery(self.view, @"pwdRepeatField") mas_makeConstraints:^(MASConstraintMaker *make) {
        make.bottom.equalTo(fQuery(self.view, @"seperLine4").mas_top).with.offset(8);
        make.height.equalTo(@48);
        make.left.equalTo(fQuery(self.view, @"seperLine4"));
        make.right.equalTo(fQuery(self.view, @"seperLine4")).with.offset(-30);;
    }];
    
    [fQuery(self.view, @"seeRepeatPwdCodeBtn") mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerY.equalTo(fQuery(self.view, @"pwdRepeatField"));
        make.right.equalTo(fQuery(self.view, @"pwdRepeatField")).with.offset(30);
        make.width.equalTo(@44);
        make.height.equalTo(@44);
    }];
    [fQuery(self.view, @"pwdRepeatLabel") mas_makeConstraints:^(MASConstraintMaker *make) {
        make.bottom.equalTo(fQuery(self.view, @"pwdRepeatField").mas_top).with.offset(4);
        make.height.equalTo(@25);
        make.left.equalTo(fQuery(self.view, @"seperLine4"));
    }];
    
    [fQuery(self.view, @"pushBtn") mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(fQuery(self.view, @"seperLine4").mas_bottom).with.offset(60);
        make.left.equalTo(fQuery(self.view, @"seperLine4"));
        make.width.equalTo(fQuery(self.view, @"seperLine4"));
        make.height.equalTo(@48);
    }];
    [fQuery(self.view, @"fClose") mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(self.view.mas_top).with.offset(10+statusBarHeight);
        make.left.equalTo(self.view.mas_left).with.offset(10);
        make.width.equalTo(@16);
        make.height.equalTo(@28);
    }];
    [fQuery(self.view, @"fClose2") mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(self.view.mas_top);
        make.left.equalTo(self.view.mas_left);
        make.width.equalTo(@100);
        make.height.equalTo(@100);
    }];
    self.txtPhone = fQueryField(self.view, @"phoneField");
    self.txtCode = fQueryField(self.view, @"yzfield");
    self.txtNewPwd = fQueryField(self.view, @"pwdfield");
    self.txtRepeatNewPwd = fQueryField(self.view, @"pwdRepeatField");
    self.txtRepeatNewPwd.delegate = self;
    
}

#pragma mark === UItextFieldDelegate ====
- (void)textFieldDidEndEditing:(UITextField *)textField{
    if(![textField.text isEqualToString:self.txtRepeatNewPwd.text]){
        [self HUDshowErrorWithStatus:@"两次输入密码不一致"];
    }
}

- (void)waitNextSend{
    self.lastSendcodeTime = [[NSDate date] timeIntervalSince1970];
    fQueryBtn(self.view, @"checkCodeBtn").enabled = NO;
    JLAsyncRun(^{
        while (YES) {
            CGFloat time = [[NSDate date] timeIntervalSince1970];
            if (time - self.lastSendcodeTime < 120) {
                JLAsyncRunInMain(^{
                    fQueryBtn(self.view, @"checkCodeBtn").fsText([NSString stringWithFormat:@"%@s",@((NSInteger)(120+self.lastSendcodeTime - time))]);
                });
            } else {
                JLAsyncRunInMain(^{
                    fQueryBtn(self.view, @"checkCodeBtn").enabled = YES;
                    fQueryBtn(self.view, @"checkCodeBtn").fsText(@"发送验证码");
                });
                break;
            }
            [NSThread sleepForTimeInterval:1];
        }
    });
}
@end
